#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include "errno.hpp"
class Sock{
public:
    static int GetListenSock(){
        int sock = socket(AF_INET,SOCK_STREAM,0);
        if(sock == -1){
            logmessage(FATAL,"%d:socket faild",SOCKETERRO);
            exit(SOCKETERRO);
        }
        return sock;
    }
    static void Bind(int sock,int port){
        sockaddr_in peer;
        memset(&peer,0,sizeof peer);
        peer.sin_family = AF_INET;
        peer.sin_addr.s_addr = INADDR_ANY;
        peer.sin_port = htons(port);
        socklen_t len = sizeof peer;
        if(bind(sock,(sockaddr*)&peer,len) == -1){
            logmessage(FATAL,"bind faild");
            exit(BINDERRO);
        }
    }
    static void Listen(int sock,int backlog){
        
        if(listen(sock,backlog) == -1){
            logmessage(FATAL,"listen faild");
            exit(LISTENERRO);
        }
    }
    static int Accept(int listensock,std::string* ip,uint16_t* port){
        sockaddr_in peer;
        socklen_t len;
        int sock = accept(listensock,(sockaddr*)&peer,&len);
        if(sock == -1){
            logmessage(WARING,"accept faild");
            *ip = "null";
            *port = -1;
        }else{
            *ip = inet_ntoa(peer.sin_addr);
            *port = ntohs(peer.sin_port);
        }

        return sock;
    }
    static void Setsockopt(int listensock){
        int opt = 1;
        if(setsockopt(listensock,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof opt) == -1){
            logmessage(WARING,"set reuseport faild!");
        }
    }
};